/**
 * 
 */
package it.unical.canonaco.rende.igpe.game.cbv.guilayer;

import java.awt.Graphics;
import java.io.File;
import java.util.concurrent.ExecutionException;

import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.SwingWorker;

/**
 * @author Massimo Canonaco
 *
 */
public abstract class AnimatedPanel extends JPanel
{
	/** */
	private Thread panelAnimator;
	
	/** */
	private final long DELAY;
	
	/** */
	private boolean animate;
	
	/** */
	private boolean ready;
	
	/** */
	private final String CONFIGURATION_FILE;// = "cbvapps"+File.separator+"uiresource"+File.separator+"mainschema.ini";
	
	/** */
	public AnimatedPanel(final long delay, final String confFile)
	{
		super();
		DELAY = delay;
		CONFIGURATION_FILE = confFile;
		load(CONFIGURATION_FILE);
		settingScene();
		ready = true;
	}
	
	abstract protected void updateScene();
	abstract protected void load(final String from);
	abstract protected void settingScene();
	
	protected void clean()
	{
		removeAll();
	}
	
	@Override
	public void addNotify() 
	{
		super.addNotify();
		animate = true;
		
		panelAnimator = new Thread(new Runnable() {
			
			@Override
			public void run() {
				long beforeTime = System.currentTimeMillis();
				
				boolean first = true;
				while(animate)
				{
					if(isReady())
					{
						if(first)
						{
							validate();
							first = false;
						}
						updateScene();
						repaint();
					}
						waitForNext(beforeTime);
					
					beforeTime = System.currentTimeMillis();
				}
			}
		});
		
		panelAnimator.start();
	}
	
	/** */
	@Override
	public void removeNotify() 
	{
		super.removeNotify();
		animate = false;
	}
	
	/** */
	private void waitForNext(final long beforeTime)
	{
		long timeDifference, sleep;
		timeDifference = System.currentTimeMillis() - beforeTime;
		sleep = DELAY - timeDifference;

		if (sleep < 0)
			sleep = 25;
		try 
		{
			Thread.sleep(sleep);
		} catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
	}

	/**
	 * @return the ready
	 */
	protected boolean isReady() {
		return ready;
	}

	/**
	 * @param ready the ready to set
	 */
	public void setReady(boolean ready) {
		this.ready = ready;
	}

	/**
	 * @return the animate
	 */
	public boolean isAnimate() {
		return animate;
	}

	/**
	 * @param animate the animate to set
	 */
	public void setAnimate(boolean animate) {
		this.animate = animate;
	}
}
